import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface User {
  id: string
  username: string
  role: 'admin' | 'user'
  realname: string
  phone?: string
  email?: string
  elderlyId: string
}

export const useUserStore = defineStore('user', () => {
  const currentUser = ref<User | null>(null)
  const token = ref<string | null>(null)

  // 默认用户（开发阶段使用）
  const defaultUser: User = {
    id: '1',
    username: 'default_user',
    role: 'admin',
    realname: '默认用户',
    phone: '13800138000',
    email: 'user@example.com',
    elderlyId: '5'
  }

  const login = (user: User, userToken: string) => {
    currentUser.value = user
    token.value = userToken
    localStorage.setItem('token', userToken)
    localStorage.setItem('user', JSON.stringify(user))
  }

  const logout = () => {
    currentUser.value = null
    token.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  const initFromStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user')
    
    if (storedToken && storedUser) {
      token.value = storedToken
      currentUser.value = JSON.parse(storedUser)
    } else {
      // 如果没有存储的用户信息，使用默认用户
      currentUser.value = defaultUser
      token.value = 'default_token'
    }
  }

  const setDefaultUser = () => {
    currentUser.value = defaultUser
    token.value = 'default_token'
  }

  return {
    currentUser,
    token,
    login,
    logout,
    initFromStorage,
    setDefaultUser
  }
}) 